<?php

class AppAction extends baseAction {

    var $Api;

    public function _initialize() {


        $this->Api = A("Api");
    }

    public function index() {

        $this->display();
    }

    public function live() {

        $members[username] = $_SESSION['username'];
        $members[uid] = $_SESSION['uid'];
        if (!empty($members)) {
            $this->assign('Example_username', $members[username]);
            $this->assign('Example_uid', $members[uid]);

            $uid = $members[uid];
            $identity = $this->Api->get_identity($uid, 2);

            $gag = $this->Api->get_gag($uid, 2);

            $this->assign('Example_identity', $identity);

            $this->assign('Example_gag', $gag);
        } else {
            $Example_uid = $Example_username = '';
            $this->assign('Example_username', '游客');
        }
        $id = (isset($_GET[id])) ? $_GET[id] : 1;
        $this->assign('id', $id);
         if (1==1) {
            $data['video_url'] = "http://o9kxq6gms.bkt.clouddn.com/%E7%88%B1%E5%89%AA%E8%BE%91-wdl.mp4";
            if (1==2) {
                $data['video_url'] = "http://o9kxq6gms.bkt.clouddn.com/%E7%88%B1%E5%89%AA%E8%BE%91-%E6%88%91%E7%9A%84%E8%A7%86%E9%A2%9112345.mp4";
            }
        }

        $this->display("room");
    }
    
    
     public function room() {

        $members[username] = $_SESSION['username'];
        $members[uid] = $_SESSION['uid'];
        if (!empty($members)) {
            $this->assign('Example_username', $members[username]);
            $this->assign('Example_uid', $members[uid]);

            $uid = $members[uid];
            $identity = $this->Api->get_identity($uid, 2);

            $gag = $this->Api->get_gag($uid, 2);

            $this->assign('Example_identity', $identity);

            $this->assign('Example_gag', $gag);
        } else {
            $Example_uid = $Example_username = '';
            $this->assign('Example_username', '游客');
        }
        $id = (isset($_GET[id])) ? $_GET[id] : 18;
        $this->assign('id', $id);

        $this->display("live");
    }

     public function ucenter() {

        $this->display("ucenter/index");
     }

      public function wechat() {

        $members[username] = $_SESSION['username'];
        $members[uid] = $_SESSION['uid'];

        // return print_r($members);
       if (!empty($members[username])) {
            $this->redirect(U('App/Room'), array(), 1, ' 已经登录!,1秒钟后页面跳转中 ~');
        } else {
           


    //判断是在微信里面打开
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') == true) {           

        //配置参数的数组
        $CONF =  array(
            '__APPID__' =>'wx2931df4a2b40b8cb',
            '__SERECT__' =>'db9a7a7ee42234a708b8e9c42d6631aa',
            '__CALL_URL__' =>'http://www.mcooz.com/App/Wechat/' //当前页地址
        );

        //没有传递code的情况下，先登录一下
        if(!isset($_GET['code']) || empty($_GET['code'])){

            $getCodeUrl  =  "https://open.weixin.qq.com/connect/oauth2/authorize".
                            "?appid=" . $CONF['__APPID__'] .
                            "&redirect_uri=" . $CONF['__CALL_URL__']  . 
                            "&response_type=code".
                            "&scope=snsapi_base". #!!!scope设置为snsapi_base !!!
                            "&state=1";

            //跳转微信获取code值,去登陆   
            header('Location:' . $getCodeUrl);
            exit;
        }

        $code           =   trim($_GET['code']);


        //使用code，拼凑链接获取用户openid 
        $getTokenUrl    =  "https://api.weixin.qq.com/sns/oauth2/access_token".
                            "?appid={$CONF['__APPID__']}".
                            "&secret={$CONF['__SERECT__']}".
                            "&code={$code}".
                            "&grant_type=authorization_code";

        $response = $this->getcurldata($getTokenUrl,array(),"get");


        $access_token = json_decode($response, true); //返回json格式数据

        $openid=$access_token['openid'];

        $url    =  "https://api.weixin.qq.com/cgi-bin/token".
                            "?appid={$CONF['__APPID__']}".
                            "&secret={$CONF['__SERECT__']}".
                            "&grant_type=client_credential";

        $response = $this->getcurldata($url,array(),"get");

        $res = json_decode($response, true); //返回json格式数据

        $access_token=$res['access_token'];

        // return print_r($access_token['openid']);

        $access['access_token']=$access_token;
        $access['openid']=$openid;

        $userInfo=$this->getUserInfo($access);

        // return print_r($this->getUserInfo($access));

            $username=$nicheng = $userInfo['nickname'];
            $password = md5(trim(123456));
            $openid=$userInfo['openid'];
            $sex=$userInfo['sex'];
            $headimgurl=$userInfo['headimgurl'];
            $city=$userInfo['city'];
            $province=$userInfo['province'];
            $country=$userInfo['country'];

            $portrait = array(0 => $headimgurl,
                                1 =>  $headimgurl,
                                2 => $headimgurl,
                                );

            $portrait = serialize($portrait);

            // echo $password;die;
           $op= M(members)->where(array('openid' =>$openid))->getField('openid');

           if (!$op) {
                    $data = array('nicheng' => $nicheng, 'password' => $password, 'username' => $username, 'openid' => $openid, 'sex' => $sex, 'portrait' => $portrait, 'city' => $city, 'province' => $province, 'country' => $country);
                    $register = M(members)->data($data)->add();

                     if ($register) {

                        Session::set('username', $username);
                        Session::set('uid', $register);

                        //print_r($register);exit();
                        $this->redirect(U('App/Room'), array(), 1, ' 注册成功!,1秒钟后页面跳转中 ~');
                        // $this->redirect(U('Member/'), array(), 2, ' 注册成功!,2秒钟后页面跳转中 ~');
                    } else {
                        $this->error('操作失败');
                    }
           } else {

            $members = M(members)->where(array('openid' => $openid))->find();
            if ($members) {
            Session::set('username', $members['username']);
            Session::set('uid', $members['uid']);
             $this->redirect(U('App/Room'), array(), 1, ' 登录成功!,1秒钟后页面跳转中 ~');

            }

           }
           

           

        // file_put_contents("test.txt", $code, FILE_APPEND);

    }
}

     }

     public function token(){
        header('content-type:text');
        ob_clean();   
            $echostr   = $_GET['echostr'];
            echo  $echostr;
/*
            $nonce     = $_GET['nonce'];
            $token     = 'weiphp';
            $timestamp = $_GET['timestamp'];
            $echostr   = $_GET['echostr'];
            $signature = $_GET['signature'];
            //形成数组，然后按字典序排序
            $array = array();
            $array = array($nonce, $timestamp, $token);
            sort($array);

            //拼接成字符串,sha1加密 ，然后与signature进行校验
            $str = sha1( implode( $array ) );

            // return print_r($str);

            file_put_contents("test.txt", "This is another something.", FILE_APPEND);


                    if( $str == $signature && $echostr ){
                    //第一次接入weixin api接口的时候
                    echo  $echostr;
                    exit;
                    }*/
     }

         /** 
         * @explain 
         * 获取到用户的openid之后可以判断用户是否有数据，可以直接跳过获取access_token,也可以继续获取access_token 
         **/  
        public function getUserInfo($access)  
        {  

            $access_token=$access['access_token'];
            $openid=$access['openid'];
            $userinfo_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token ."&openid=" . $openid."&lang=zh_CN";  
            $userinfo_json = $this->getcurldata($userinfo_url,array(),"get");  
            $userinfo_array = json_decode($userinfo_json, TRUE);  
            return $userinfo_array;  
        }  

        /** 
         * @QQ315902734 
         * 师兄圈 
         **/  
        public function circle() 
        {  

            $this->display("circle");

        }

}
